package com.zjuee.core.utils;

import com.zjuee.base.bean.response.CommonResultCode;
import com.zjuee.base.exception.BaseException;
import com.zjuee.base.utils.Base64Utils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author wu liang
 * @since 1.0
 */
public class ExcelUtil<T> {

    //每次设置导出数量
    public static int  NUM=5000;
    public static String title="";

    //获取文件名字
    public static String getFileName(){
        // 文件名获取
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String f = title + format.format(date);
        return f;
    }
    //压缩文件
    public static void ZipFiles(java.io.File[] srcfile, java.io.File zipfile) {
        byte[] buf = new byte[1024];
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                    zipfile));
            for (int i = 0; i < srcfile.length; i++) {
                FileInputStream in = new FileInputStream(srcfile[i]);
                out.putNextEntry(new ZipEntry(srcfile[i].getName()));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 设置响应头 */
//    public void setResponseHeader(HttpServletResponse response, String fileName) {
//        try {
//            this.title=fileName;
//            response.reset();// 清空输出流
//            response.setContentType("application/octet-stream;charset=UTF-8");
//            response.setHeader("Content-Disposition", "attachment;filename="
//                    +new String(this.title.getBytes("GB2312"), "8859_1")
//                    + ".zip");
//            response.addHeader("Pargam", "no-cache");
//            response.addHeader("Cache-Control", "no-cache");
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//    }

//    private void test(){
//        try {
//            HSSFWorkbook workbook = new HSSFWorkbook();
//            OutputStream out = response.getOutputStream();
//            for(int j=0;j<n;j++){
//                BaseResult<List<T>> teasalList = service.select(teasal);
//                //接下来循环list放到Excel表中
//                if(teasalList.isSuccess()&&teasalList.getResult().size()>0){
//                    //文件标题
//                    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
//                    String nowdate = formatter1.format(new Date());
//                    String title = null;
//                    title = "excel表格标题-" + nowdate + ".xls";
//                    String sheettitle = "sheet表名";
//                    //设置表格标题行
//                    String oneheaders = "首行标题" ;
//                    String dateheaders = nowdate ;
//                    String[] headers = new String[] {"列1","列2","列3","列4"};
//                    List<Object[]> dataList = new ArrayList<Object[]>();
//                    Object[] objs = null;
//                    for(int i =0; i<3 ; i++){  //循环每一条数据
//                        objs = new Object[headers.length];
//                        objs[1] = "张三";   //姓名
//                        objs[2] = "3";  //序号
//                        //数据添加到excel表格
//                        dataList.add(objs);
//                    }
//                    //使用流将数据导出
//                    //防止中文乱码
//                    String headStr = "attachment; filename=\"" + new String( title.getBytes("gb2312"), "ISO8859-1" ) + "\"";
//                    response.setContentType("octets/stream");
//                    response.setContentType("APPLICATION/OCTET-STREAM");
//                    response.setHeader("Content-Disposition", headStr);
//                    ExportExcelDownFee ex ;
//                    ex = new ExportExcelDownFee(sheettitle, oneheaders, dateheaders,headers, dataList);//没有标题
//                    ex.export(workbook);
//                }
//            }
//            workbook.write(out);  //循环生成多个sheet之后在导出Excel
//            out.close();  //关闭流
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    //todo 是否完善太多数据的分sheet
    void test1(){
//        int n=0;
//        if (!CollectionUtils.isEmpty(result)) {
//            if (result.size() % NUM == 0) {
//                n = result.size() / NUM;
//            } else {
//                n = result.size() / NUM + 1;
//            }
//        }else{
//            n=1;
//        }
//        List<String> fileNames = new ArrayList();// 用于存放生成的文件名称s
//        //文件流用于转存文件
//
//        for (int j = 0; j < n; j++) {
//            Collection<T> result1=null;
//            //切取每5000为一个导出单位，存储一个文件
//            //对不足5000做处理；
//            if (!CollectionUtils.isEmpty(result)) {
//                if (j == n - 1) {
//                    if (result.size() % NUM == 0) {
//                        result1 = result.subList(5000 * j, 5000 * (j + 1));
//                    } else {
//                        result1 = result.subList(5000 * j,
//                                5000 * j + result.size() % NUM);
//                    }
//                } else {
//                    result1 = result.subList(5000 * j, 5000 * (j + 1));
//                }
//            }
//        }
    }

    /**
     * 导出
     *
     * @param request  HttpServletRequest对象，用于获取用户浏览器类型
     * @param response HttpServletResponse对象，用于写入Excel输出流
     */
    public static void download(String fileName, List<ExportExcel> sheets,
                                HttpServletRequest request ,HttpServletResponse response) {
        try {
            // 生成Excel
            Workbook workbook = new HSSFWorkbook();
            for(ExportExcel exportExcel : sheets){
                ExportExcelDownFee ex ;
                ex = new ExportExcelDownFee(exportExcel);//没有标题
                ex.export(workbook);
            }
            // 设置response参数，可以打开下载页面
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            OutputStream os = response.getOutputStream();
            // 根据浏览器，设置文件名
            String userAgent = request.getHeader("user-agent");
            if (userAgent.contains("Firefox")) {
                fileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes(StandardCharsets.UTF_8)) + "?=";
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");

            // Excel写到浏览器输出流
            workbook.write(os);
            os.close();
            workbook.close();
        } catch (IOException e) {
            throw new BaseException(CommonResultCode.CONSUMER_ERR, "Excel下载失败！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


//    public static void main(String[] args) {
//        String agent = request.getHeader("USER-AGENT");
//        boolean isIe = null != agent && agent.contains("MSIE") || null != agent
//                && agent.contains("Trident") || null != agent && agent.contains("Edge");
//        if (isIe) {
//            // ie
//            String fileName = java.net.URLEncoder.encode(excelName, "UTF8");
//            response.addHeader("Content-Disposition", "attachment;filename="
//                    + fileName + ".xlsx");
//        } else if (null != agent && agent.contains("Mozilla")) {
//            // 火狐,chrome等
//            String fileName = new String(excelName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
//            response.addHeader("Content-Disposition", "attachment;filename="
//                    + fileName + ".xlsx");
//        }
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//
//        // 直接写入response的输出流
//        workbook.write(response.getOutputStream());
//    }

}
